using FirstTea.Application.DTOs;
using FirstTea.Application.Interfaces;
using FirstTea.Domain.Entities;
using FirstTea.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstTea.Application.Services
{
    public class ConversationService : IConversationService
    {
        private readonly IRepository<Conversation> _conversationRepo;
        public ConversationService(IRepository<Conversation> conversationRepo)
        {
            _conversationRepo = conversationRepo;
        }
        public async Task<ConversationDto?> GetByIdAsync(Guid id)
        {
            if (id == Guid.Empty) throw new ArgumentException("会话Id不能为空");
            var conv = await _conversationRepo.GetByIdAsync(id);
            if (conv == null) return null;
            return new ConversationDto { Id = conv.Id, UserId = conv.UserId, SellerId = conv.SellerId, Message = conv.Message, SentAt = conv.SentAt };
        }
        public async Task<IEnumerable<ConversationDto>> GetAllAsync()
        {
            var convs = await _conversationRepo.GetAllAsync();
            return convs.Select(c => new ConversationDto { Id = c.Id, UserId = c.UserId, SellerId = c.SellerId, Message = c.Message, SentAt = c.SentAt });
        }
        public async Task<IEnumerable<ConversationDto>> GetByUserAsync(Guid userId)
        {
            var convs = await _conversationRepo.FindAsync(c => c.UserId == userId || c.SellerId == userId);
            return convs.Select(c => new ConversationDto { Id = c.Id, UserId = c.UserId, SellerId = c.SellerId, Message = c.Message, SentAt = c.SentAt });
        }
        public async Task CreateAsync(ConversationDto dto)
        {
            if (dto == null) throw new ArgumentNullException(nameof(dto));
            var conv = new Conversation { UserId = dto.UserId, SellerId = dto.SellerId, Message = dto.Message, SentAt = dto.SentAt };
            await _conversationRepo.AddAsync(conv);
            await _conversationRepo.SaveChangesAsync();
        }
        public async Task DeleteAsync(Guid id)
        {
            await _conversationRepo.DeleteAsync(id);
            await _conversationRepo.SaveChangesAsync();
        }
    }
}
